package com.zkj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zkj.constant.MessageConstant;
import com.zkj.constant.PasswordConstant;
import com.zkj.constant.StatusConstant;
import com.zkj.context.BaseContext;
import com.zkj.dto.EmployeeDTO;
import com.zkj.entity.Employee;
import com.zkj.exception.AccountDisabledException;
import com.zkj.exception.AccountNotFountException;
import com.zkj.exception.PasswordErrorException;
import com.zkj.mapper.EmployeeMapper;
import com.zkj.result.Result;
import com.zkj.service.IEmployeeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zkj.validator.PhoneNumberValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 员工信息 服务实现类
 * </p>
 *
 * @author zkj
 * @since 2024-08-22
 */
@Service
@Slf4j
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public Result addEmployee(EmployeeDTO employeeDTO) {
        String username = employeeDTO.getUsername();

        Employee employeeByUsername = employeeMapper.selectEmployeeByUsername(username);

        if (employeeByUsername != null) {
            return Result.error("用户名已存在");
        }

        String idNumber = employeeDTO.getIdNumber();
        String phone = employeeDTO.getPhone();

        if (StringUtils.isEmpty(idNumber) || idNumber.length() != 18) {
            return Result.error("身份证号格式不正确");
        }
        if (StringUtils.isEmpty(phone) || !PhoneNumberValidator.isValidPhoneNumber(phone)) {
            return Result.error("手机号格式不正确");
        }

        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employee.setStatus(StatusConstant.Enabled);
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.PASSWORD.getBytes()));

        // 设置当前记录的创建时间和修改时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        // 设置当前记录的操作用户
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());

        log.info("EmployeeServiceImpl.addEmployee: {}", employee);
        int i = employeeMapper.insert(employee);
        if (i > 0) {
            return Result.success().message("添加成功");
        } else {
            return Result.error("添加失败");
        }
    }

    @Override
    public Employee login(EmployeeDTO employeeDTO) {

        String username = employeeDTO.getUsername();
        String password = employeeDTO.getPassword();

        Employee employee = employeeMapper.selectEmployeeByUsername(username);
        if (employee == null) {
            // 用户不存在
            throw new AccountNotFountException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(employee.getPassword())) {
            // 密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.Disabled) {
            // 账号被禁用
            throw new AccountDisabledException(MessageConstant.ACCOUNT_DISABLE);
        }
        return employee;
    }

    @Override
    public Result page(Integer pageNum, Integer pageSize, String name)  {
        IPage<Employee> pageParam = new Page(1, 10);
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();

        if (name != null && name.trim().length() > 0) {
            queryWrapper.like("name", name);
        }


        IPage<Employee> employeeIPage = employeeMapper.selectPage(pageParam, queryWrapper);
        return Result.success(employeeIPage);
    }

    @Override
    public Result setEmployeeStatus(Long id, Integer statusNum) {
        Employee employee = employeeMapper.selectById(id);
        if (employee == null) {
            throw new AccountNotFountException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        employee.setStatus(statusNum);
        int number = employeeMapper.updateById(employee);
        if (number > 0) {
            return Result.success().message("操作成功");
        } else {
            return Result.error("操作失败");
        }
    }

    @Override
    public Result updateUserInfo(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);

        // 设置修改时间和修改人 - 已使用注解完成
//        employee.setUpdateUser(BaseContext.getCurrentId());
//        employee.setUpdateTime(LocalDateTime.now());

        int i = employeeMapper.updateById(employee);
        if (i > 0) {
            return Result.success().message("操作成功");
        } else {
            return Result.error("操作失败");
        }
    }
}
